package com.lhkj.ct.wechat.controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.TypeReference;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.ApiSupport;
import com.lhkj.ct.base.constants.ConfigConstants;
import com.lhkj.ct.base.enums.IamsServiceEnum;
import com.lhkj.ct.base.model.ro.ActionResult;
import com.lhkj.ct.base.utils.MessageUtils;
import com.lhkj.ct.base.utils.ShiroUtil;
import com.lhkj.ct.base.utils.http.HttpUtils;
import com.lhkj.ct.framework.auth.dto.PatRegisterDto;
import com.lhkj.ct.framework.auth.ro.WxJsapiSignature;
import com.lhkj.ct.framework.auth.service.AuthService;
import com.lhkj.ct.framework.shiro.token.AccessTokenAuthenticationToken;
import com.lhkj.ct.meta.admin.service.SysConfigService;
import com.lhkj.ct.meta.modules.auth.common.enums.IdentType;
import com.lhkj.ct.meta.modules.auth.common.enums.UserType;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;

/**
  * <p>
  *     描述：公众号授权
  * </p>
  */
@Controller
@RequestMapping("api/wechat/auth")
@Api(tags = {"01.授权接口"})
@ApiSupport(order = 1)
public class WeChatAuthController {
    private static final Logger log = LoggerFactory.getLogger(WeChatAuthController.class);

    @Resource
    private AuthService authService;

    @Resource
    private SysConfigService sysConfigService;

    @ApiOperation(value = "测试登录")
    @ApiOperationSupport(order = 1)
    @RequestMapping("login")
    public void login(HttpServletResponse response) throws IOException {
        AccessTokenAuthenticationToken token = new AccessTokenAuthenticationToken(UserType.PLATFORM, "o52zO6etDI_PVOSAO84OmmFY08AE", IdentType.WXP);
        Subject subject = ShiroUtil.getSubject();
        // 其他时间 单位毫秒,如下设置一周
        subject.getSession().setTimeout(7 * 24 * 60 * 60 * 1000L);
        subject.login(token);
        String sessionId = subject.getSession().getId().toString();
        response.getWriter().write(JSON.toJSONString(ActionResult.success(MessageUtils.message("user.login.success"), sessionId)));
        // 已登录
//        if (ShiroUtil.getSubject().isAuthenticated()){
//            response.setCharacterEncoding("UTF-8");
//            response.getWriter().write(JSON.toJSONString(ActionResult.success(MessageUtils.message("user.login.success"), ShiroUtil.getSession().getId())));
//            return;
//        }
//        return "redirect:http://www.hnlhtech.com/service/api/iams/mp/authorize";
    }

    @ApiOperation(value = "授权回调")
    @ApiOperationSupport(order = 1)
    @GetMapping(value = "wechatLogin")
    public void wechatLogin(@RequestParam String code, @RequestParam(required = false) String url, HttpServletResponse response) throws IOException {
        log.debug("进入公众号授权回调，code：{}, url：{}", code, url);
        authService.wechatLogin(code, response);
    }

    @ResponseBody
    @ApiOperation(value = "建卡")
    @ApiOperationSupport(order = 1)
    @PostMapping("register")
    public ActionResult<String> register(@Validated @RequestBody PatRegisterDto registerDto) {
        return ActionResult.success(MessageUtils.message("user.register.success"),authService.register(registerDto));
    }

    @ResponseBody
    @ApiOperation(value = "获取js-sdk参数")
    @ApiOperationSupport(order = 1)
    @GetMapping("JsapiSignature")
    public ActionResult<?> createJsapiSignature(@RequestParam String url) {
        HashMap<String, Object> map = new HashMap<>();
        String appid = sysConfigService.selectConfigByKey(ConfigConstants.SYS_WECHAT_APPID);
        map.put("mpId", appid);
        map.put("url", url);
        String jsonResult = HttpUtils.sendGet(IamsServiceEnum.JSAPI_SIGNATURE_URL.getUrl(), map);
        try {
            return JSONObject.parseObject(jsonResult, new TypeReference<ActionResult<WxJsapiSignature>>() {});
        } catch (Exception e) {
            log.error("获取js-sdk签名异常：{}",e.getMessage());
            return ActionResult.fail("获取js-sdk签名异常");

        }
    }

}
